package com.songshan.controller;

import com.songshan.bean.User;
import com.songshan.dto.PageParameter;
import com.songshan.dto.Result;
import com.songshan.dto.UserDto;
import com.songshan.exception.BusinessException;
import com.songshan.service.UserManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author feb
 * @date 2024/6/18
 * @Description: 用户管理
 */
@Controller
@RequestMapping(value = "/user")
public class UserManageController {

  @Autowired
  private UserManageService userManageService;

  /**
   * @author feb
   * @date 2024/6/18
   * @Description: 用户管理页面
   */
  @GetMapping("manage.htmlx")
  public String userManage() {
    return "userManage";
  }

  /**
   * @author feb
   * @date 2024/6/18
   * @Description: 用户详情页面
   */
  @RequestMapping("detail.htmlx")
  public String userDetail() {
    return "userDetail";
  }

  /**
   * @author feb
   * @date 2024/6/18
   * @Description: 用户详情查询
   */
  @PostMapping("queryDetail.do")
  @ResponseBody
  public User queryUserDetail(Integer id) {
    return userManageService.queryUserDetail(id);
  }

  /**
   * @author feb
   * @date 2024/6/18
   * @Description: 用户管理列表
   */
  @PostMapping("queryWithPage.do")
  @ResponseBody
  public Map<String, Object> queryUserWithPage(@RequestBody PageParameter queryParameter) {
    return userManageService.queryUserWithPage(queryParameter);
  }

  /**
   * @author feb
   * @date 2024/6/18
   * @Description: 用户保存
   */
  @PostMapping("save.do")
  @ResponseBody
  public Result saveUser(MultipartFile file, @Valid UserDto userDto, BindingResult errors)
      throws BusinessException {
    if (errors.hasErrors()) {
      return Result.failure(errors.getFieldErrors());
    } else {
      if (userDto.getId() == null) {
        userManageService.addUser(file, userDto);
      } else {
        userManageService.modUser(file, userDto);
      }
    }
    return Result.success();
  }

  /**
   * @author feb
   * @date 2024/6/18
   * @Description: 用户删除
   */
  @PostMapping("del.do")
  @ResponseBody
  public Result delUser(Integer id) throws BusinessException{
    userManageService.delUser(id);
    return Result.success();
  }

  /**
   * @author feb
   * @date 2024/6/19
   * @Description: 用户状态操作
   */
  @PostMapping("userStatus.do")
  @ResponseBody
  public Result userStatus(Integer id,Integer status) throws BusinessException{
    userManageService.userStatus(id,status);
    return Result.success();
  }

  /**
   * @author feb
   * @date 2024/6/18
   * @Description: 用户授权
   */
  @PostMapping("addRole.do")
  @ResponseBody
  public Result addRole(@RequestBody Map<String, Object> param) throws BusinessException{
    userManageService.addRole(param);
    return Result.success();
  }

}
